import {
  customerList,
  getLicenseByPage,
  getLicenseOriginalViewByPage,
  getLicenseNextgoingViewByPage,
} from '@/services/sales/license';
import type { ProColumns } from '@ant-design/pro-table';
import { ProFormInstance, ProCard } from '@ant-design/pro-components';
import ProTable from '@ant-design/pro-table';
import { Select, Tag, Card } from 'antd';
import { Spin } from 'antd';
import type { SelectProps } from 'antd/es/select';
import debounce from 'lodash/debounce';
import React, { useMemo, useRef, useState, useEffect } from 'react';

export interface DebounceSelectProps<ValueType = any>
  extends Omit<SelectProps<ValueType | ValueType[]>, 'options' | 'children'> {
  fetchOptions: (search: string) => Promise<ValueType[]>;
  debounceTimeout?: number;
}

// Usage of DebounceSelect
interface UserValue {
  label: string;
  value: string;
}

type TableListItem = {
  usedtime?: Date;
  usedNum: number;
  usedName: string;
};

type DetailListProps = {
  licenseID: string;
};

//#region 详情组件

export const DetailList: React.FC<DetailListProps> = (props) => {
  const { licenseID } = props;
  const [tableListDataSource, setTableListDataSource] = useState<TableListItem[]>([]);
  const formRef = useRef<
    ProFormInstance<{
      name: string;
      company?: string;
      useMode?: string;
    }>
  >();
  const nextgoingMap = new Map([
    [1, '使用'],
    [2, '转让'],
  ]);

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '使用时间',
      dataIndex: 'useTime',
      search: false,
      width: 160,
    },
    {
      title: '使用时间', //表头显示的名称
      valueType: 'dateRange',
      hideInTable: true,
      dataIndex: 'useTime',
    },
    {
      title: '订货号',
      key: 'orderId',
      dataIndex: 'orderId',
    },
    {
      title: '授权号类型', //表头显示的名称
      search: false,
      dataIndex: 'licenseType', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      // width: 100,
      render: (_, record) => <Tag color={'green'}>{licenseTypeMap.get(record.licenseType)}</Tag>,
    },
    {
      title: '授权号类型',
      dataIndex: 'licenseType',
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        1: 'BD推广',
        2: '基础版',
        // 3: '尊享版',
        // 4: '高级版',
        // 5: '10Package',
        // 6: '50Package',
        7: '堆垛机版',
      },
    },
    {
      title: '已用数量',
      key: 'usedNum',
      dataIndex: 'usedNum',
      search: false,
    },
    {
      title: '去向',
      key: 'nextGoing',
      search: false,
      dataIndex: 'nextGoing',
      render: (_, record) => <Tag color={'blue'}>{nextgoingMap.get(record.nextGoing)}</Tag>,
    },
    {
      title: '去向',
      key: 'nextGoing',
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        1: '使用',
        2: '转让',
      },
    },
    {
      title: '所属客户',
      key: 'nextGoingName',
      dataIndex: 'nextGoingName',
    },
  ];

  useEffect(() => {
    let source = [];

    console.log(licenseID);
    (async (params = {}, sort, filter) => {
      console.log(params);
      const result = await getLicenseNextgoingViewByPage({ ...params, current: 1, pageSize: 10 });
      setTableListDataSource(result?.data?.content);
    })();
  }, [licenseID]);
  return (
    <ProTable<TableListItem>
      columns={columns}
      rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
      request={async (params = {}, sort, filter) => {
        console.log(params);
        const result = await getLicenseNextgoingViewByPage({ ...params, id: licenseID });
        return {
          data: result.data.content,
          total: result.data.totalElements,
          success: result.success,
        };
      }}
      pagination={{
        pageSize: 10,
        showSizeChanger: false,
      }}
      toolBarRender={false}
    ></ProTable>
  );
};
//#endregion
//#region 主表组件

export type LicenseListItem = {
  licenseID?: string;
  licenseType?: number | string;
  purchaseTime?: Date;
  num?: number | string;
  usedNum?: number;
  notUsedNum?: number;
};

const licenseListDataSource: any = [];

type LicenseListProps = {
  licenseID: string;
  onChange: (licenseID: string) => void;
};

const licenseTypeMap = new Map([
  [1, 'BD推广'],
  [2, '基础版'],
  [3, '尊享版'],
  [4, '高级版'],
  [5, '10Package'],
  [6, '50Package'],
  [7, '堆垛机版'],
]);

const originalMap = new Map([
  [1, 'GMC'],
  [2, '转让'],
]);

const LicenseList: React.FC<LicenseListProps> = (props) => {
  const { onChange, licenseID } = props;

  const columns: ProColumns<LicenseListItem>[] = [
    {
      title: '订货号',
      key: 'orderId',
      dataIndex: 'orderId',
    },
    {
      title: '授权号类型', //表头显示的名称
      search: false,
      dataIndex: 'licenseType', // 列数据在数据项中对应的路径，支持通过数组查询嵌套路径
      width: 100,
      render: (_, record) => <Tag color={'green'}>{licenseTypeMap.get(record.licenseType)}</Tag>,
    },
    {
      title: '授权号类型',
      dataIndex: 'licenseType',
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        1: 'BD推广',
        2: '基础版',
        // 3: '尊享版',
        // 4: '高级版',
        // 5: '10Package',
        // 6: '50Package',
        7: '堆垛机版',
      },
    },
    {
      title: '来源',
      key: 'original',
      search: false,
      dataIndex: 'original',
      render: (_, record) => <Tag color={'blue'}>{originalMap.get(record.original)}</Tag>,
    },
    {
      title: '来源',
      dataIndex: 'original',
      hideInTable: true,
      valueType: 'select',
      valueEnum: {
        1: 'GMC',
        2: '转让',
      },
    },
    {
      title: '购买时间',
      key: 'purchaseTime',
      dataIndex: 'purchaseTime',
      search: false,
    },
    {
      title: '购买时间', //表头显示的名称
      valueType: 'dateRange',
      hideInTable: true,
      dataIndex: 'purchaseTime',
    },
    {
      title: '授权号数量',
      key: 'tolNum',
      dataIndex: 'tolNum',
    },
  ];
  return (
    <div>
      <ProTable //表格Pro组件
        headerTitle="授权号查询" //表头
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        request={async (params = {}, sort, filter) => {
          console.log(params);
          const result = await getLicenseOriginalViewByPage({ ...params, id: licenseID });
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        pagination={{
          pageSize: 5,
          showSizeChanger: true,
        }}
        columns={columns} //上面定义的
        rowSelection={{}}
        onRow={(record) => {
          return {
            onClick: () => {
              if (record.licenseID) {
                onChange(record.licenseID);
              }
            },
          };
        }}
      />
    </div>
  );
};
//#endregion

const operationTabList = [
  {
    key: 'purchaseInfo',
    tab: (
      <span>
        购买详情 <span style={{ fontSize: 14 }}></span>
      </span>
    ),
  },
  {
    key: 'usedInfo',
    tab: (
      <span>
        使用详情 <span style={{ fontSize: 14 }}></span>
      </span>
    ),
  },
];
export type tabKeyType = 'purchaseInfo' | 'usedInfo';
// 左右结构表格组件
const licenseCustom: React.FC<{}> = () => {
  const [tabKey, setTabKey] = useState<tabKeyType>('purchaseInfo');

  // 渲染tab切换
  const renderChildrenByTabKey = (tabValue: tabKeyType) => {
    if (tabValue === 'purchaseInfo') {
      return <LicenseList onChange={(cIp) => setLicenseID(cIp)} licenseID={licenseID} />;
    }
    if (tabValue === 'usedInfo') {
      return <DetailList licenseID={licenseID} />;
    }
  };
  const [licenseID, setLicenseID] = useState('');

  return (
    <Card
      bordered={false}
      tabList={operationTabList}
      activeTabKey={tabKey}
      onTabChange={(_tabKey: string) => {
        setTabKey(_tabKey as tabKeyType);
      }}
    >
      {renderChildrenByTabKey(tabKey)}
    </Card>
  );
};

export default licenseCustom;
